const express = require('express');
const router = express.Router();
const connection = require('./db.js'); // 确保 db.js 正确设置了数据库连接

/*请求方式：http://127.0.0.1:3000/api/nearest/nearestLocation
json
{  
  "latitude": 34,  
  "longitude": 354  
   
}
这个通过前端发送


返回json
{
    "spotname": "教学楼",
    "latitude": "35",
    "longitude": "352",
    "description": "542",
    "distance": 2.23606797749979
}

*/
router.post('/nearestLocation', (req, res) => {
    const { latitude, longitude } = req.body;

    if (typeof latitude !== 'number' || typeof longitude !== 'number') {
        return res.status(400).json({ error: 'Please provide valid latitude and longitude' });
    }

    const query = `
        SELECT spotname, latitude, longitude, description,
        SQRT(POW(latitude - ?, 2) + POW(longitude - ?, 2)) AS distance
        FROM locations
        ORDER BY distance
        LIMIT 1
    `;

    connection.query(query, [latitude, longitude], (err, results) => {
        if (err) {
            console.error('Error querying database: ' + err.stack);
            return res.status(500).json({ error: 'Internal server error' });
        }

        if (results.length === 0) {
            return res.status(404).json({ error: 'No locations found' });
        }

        const nearestLocation = results[0];
        res.json({
            spotname: nearestLocation.spotname,
            latitude: nearestLocation.latitude,
            longitude: nearestLocation.longitude,
            description: nearestLocation.description,
            distance: nearestLocation.distance
        });
    });
});

module.exports = router;